package com.example.upgradesystem.controller;

import com.example.upgradesystem.model.User;
import com.example.upgradesystem.repository.UserRepository;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Resource
    private UserRepository userRepository;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestParam("username") String username,
                                      @RequestParam("password") String password) {
        // 创建User对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password); // 这里应使用加密后的密码
        user.setRole("USER");

        // 保存到数据库
        userRepository.save(user);

        return ResponseEntity.ok("User registered successfully.");
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam("username") String username,
                                   @RequestParam("password") String password) {
        // 查找用户
        User user = userRepository.findByUsernameAndPassword(username, password);
        if (user != null) {
            return ResponseEntity.ok("Login successful.");
        } else {
            return ResponseEntity.status(401).body("Invalid credentials.");
        }
    }
}